package com.game.message.jpb.codec;

import com.game.message.Msg;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class JPbDecoder extends ByteToMessageDecoder {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	public final static int DATA_LENGTH = 4;

	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		if (in.readableBytes() < DATA_LENGTH) {
			return;
		}
		in.markReaderIndex();
		int dataLength = in.readInt();
		if (in.readableBytes() < dataLength) {
			in.resetReaderIndex();
			return;
		}
		//int sid = in.readInt();
		int msgId = in.readInt();
		byte[] decoded = new byte[dataLength - DATA_LENGTH * 2];
		in.readBytes(decoded);
		Msg msg = new Msg();
		msg.setMsgId(msgId);
		msg.setBody(decoded);
		out.add(msg);
	}

   /* *//**
	 * @param maxFrameLength
	 * @param lengthFieldOffset
	 * @param lengthFieldLength
	 *//*
	public JPbDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf frame = (ByteBuf) super.decode(ctx, in);
        if (frame == null) {
            return null;
        }
        int readableBytes = frame.readableBytes();
        byte [] body = new byte[readableBytes];
        for (int i = 0; i < readableBytes; i++) {
            body[i] = frame.readByte();
        }
        return body;
    }
*/
}
